package com.property.demo.controller;

import com.property.demo.dto.ApiResponse;
import com.property.demo.dto.HomeDTO;
import com.property.demo.dto.OwnerDTO;
import com.property.demo.model.Home;
import com.property.demo.model.Owner;
import com.property.demo.repository.HomeRepository;
import com.property.demo.repository.OwnerRepository;
import com.property.demo.service.OwnerService;
import com.property.demo.util.DTOMapper;
import com.property.demo.util.ExcelUtil;
import com.property.demo.util.SortUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/owners")
public class OwnerController {

    private static final Logger logger = LoggerFactory.getLogger(OwnerController.class);

    @Autowired
    private OwnerRepository ownerRepository;
    
    @Autowired
    private HomeRepository homeRepository;
    
    @Autowired
    private OwnerService ownerService;

    // 获取所有业主（分页）
    @GetMapping
    public ResponseEntity<?> getAllOwners(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String phoneNumber,
            @RequestParam(required = false) String idCard,
            @RequestParam(defaultValue = "id,desc") String[] sort) {
        
        try {
            List<Sort.Order> orders = SortUtil.getOrders(sort);
            Pageable pageable = PageRequest.of(page, size, Sort.by(orders));
            
            Page<Owner> ownersPage;
            if ((name != null && !name.isEmpty()) || (phoneNumber != null && !phoneNumber.isEmpty()) || (idCard != null && !idCard.isEmpty())) {
                ownersPage = ownerService.findByFilters(name, phoneNumber, idCard, pageable);
            } else {
                ownersPage = ownerService.findAll(pageable);
            }
            
            List<OwnerDTO> ownerDTOs = ownersPage.getContent().stream()
                    .map(DTOMapper::toOwnerDTO)
                    .collect(Collectors.toList());
            
            // 为每个业主添加房产信息
            for (OwnerDTO ownerDTO : ownerDTOs) {
                List<Home> homes = homeRepository.findByOwnerId(ownerDTO.getId());
                List<HomeDTO> homeDTOs = DTOMapper.toHomeDTOList(homes);
                ownerDTO.setHomes(homeDTOs);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("content", ownerDTOs);
            response.put("currentPage", ownersPage.getNumber());
            response.put("totalItems", ownersPage.getTotalElements());
            response.put("totalPages", ownersPage.getTotalPages());
            
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(
                new ApiResponse(false, "获取业主列表失败: " + e.getMessage()),
                HttpStatus.INTERNAL_SERVER_ERROR
            );
        }
    }

    // 获取所有业主（不分页）
    @GetMapping("/all")
    public ResponseEntity<List<OwnerDTO>> getAllOwnersNoPage() {
        List<Owner> owners = ownerRepository.findAll();
        List<OwnerDTO> ownerDTOs = DTOMapper.toOwnerDTOList(owners);
        
        // 为每个业主添加房产信息
        for (OwnerDTO ownerDTO : ownerDTOs) {
            List<Home> homes = homeRepository.findByOwnerId(ownerDTO.getId());
            List<HomeDTO> homeDTOs = DTOMapper.toHomeDTOList(homes);
            ownerDTO.setHomes(homeDTOs);
        }
        
        return ResponseEntity.ok(ownerDTOs);
    }

    // 根据ID获取业主
    @GetMapping("/{id}")
    public ResponseEntity<?> getOwnerById(@PathVariable Long id) {
        Optional<Owner> owner = ownerRepository.findById(id);
        if (owner.isPresent()) {
            OwnerDTO ownerDTO = DTOMapper.toOwnerDTO(owner.get());
            
            // 添加房产信息
            List<Home> homes = homeRepository.findByOwnerId(id);
            List<HomeDTO> homeDTOs = DTOMapper.toHomeDTOList(homes);
            ownerDTO.setHomes(homeDTOs);
            
            return ResponseEntity.ok(ownerDTO);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 创建业主
    @PostMapping
    public ResponseEntity<?> createOwner(@RequestBody Owner owner) {
        Owner savedOwner = ownerRepository.save(owner);
        OwnerDTO ownerDTO = DTOMapper.toOwnerDTO(savedOwner);
        return ResponseEntity.ok(new ApiResponse(true, "业主创建成功", ownerDTO));
    }

    // 更新业主
    @PutMapping("/{id}")
    public ResponseEntity<?> updateOwner(@PathVariable Long id, @RequestBody Owner ownerDetails) {
        Optional<Owner> owner = ownerRepository.findById(id);
        if (owner.isPresent()) {
            Owner existingOwner = owner.get();
            existingOwner.setName(ownerDetails.getName());
            existingOwner.setGender(ownerDetails.getGender());
            existingOwner.setPhoneNumber(ownerDetails.getPhoneNumber());
            existingOwner.setIdCard(ownerDetails.getIdCard());
            existingOwner.setProfession(ownerDetails.getProfession());
            existingOwner.setEmail(ownerDetails.getEmail());
            existingOwner.setRemarks(ownerDetails.getRemarks());
            
            Owner updatedOwner = ownerRepository.save(existingOwner);
            OwnerDTO ownerDTO = DTOMapper.toOwnerDTO(updatedOwner);
            return ResponseEntity.ok(new ApiResponse(true, "业主更新成功", ownerDTO));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 删除业主
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteOwner(@PathVariable Long id) {
        Optional<Owner> owner = ownerRepository.findById(id);
        if (owner.isPresent()) {
            ownerRepository.deleteById(id);
            return ResponseEntity.ok(new ApiResponse(true, "业主删除成功"));
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    // 批量删除业主
    @DeleteMapping("/batch")
    public ResponseEntity<?> batchDeleteOwners(@RequestBody List<Long> ids) {
        ownerRepository.deleteAllById(ids);
        return ResponseEntity.ok(new ApiResponse(true, "业主批量删除成功"));
    }
    
    // 根据名称搜索业主
    @GetMapping("/search")
    public ResponseEntity<List<OwnerDTO>> searchOwners(@RequestParam(required = false) String name, 
                                                   @RequestParam(required = false) String phoneNumber) {
        List<Owner> owners;
        if (name != null && !name.isEmpty()) {
            owners = ownerRepository.findByNameContaining(name);
        } else if (phoneNumber != null && !phoneNumber.isEmpty()) {
            owners = ownerRepository.findByPhoneNumber(phoneNumber);
        } else {
            owners = ownerRepository.findAll();
        }
        List<OwnerDTO> ownerDTOs = DTOMapper.toOwnerDTOList(owners);
        
        // 为每个业主添加房产信息
        for (OwnerDTO ownerDTO : ownerDTOs) {
            List<Home> homes = homeRepository.findByOwnerId(ownerDTO.getId());
            List<HomeDTO> homeDTOs = DTOMapper.toHomeDTOList(homes);
            ownerDTO.setHomes(homeDTOs);
        }
        
        return ResponseEntity.ok(ownerDTOs);
    }

    // 导出所有业主
    @GetMapping("/export")
    public void exportOwners(HttpServletResponse response) {
        try {
            List<Owner> owners = ownerRepository.findAll();
            List<OwnerDTO> ownerDTOs = DTOMapper.toOwnerDTOList(owners);
            
            // 定义表头
            List<Map<String, Object>> headers = new ArrayList<>();
            headers.add(createHeader("姓名", "name", 15));
            headers.add(createHeader("性别", "gender", 10));
            headers.add(createHeader("电话号码", "phoneNumber", 20));
            headers.add(createHeader("身份证号", "idCard", 25));
            headers.add(createHeader("职业", "profession", 15));
            headers.add(createHeader("邮箱", "email", 25));
            headers.add(createHeader("备注", "remarks", 30));
            
            // 导出Excel
            ExcelUtil.exportExcel(response, "业主信息表", ownerDTOs, headers);
        } catch (Exception e) {
            e.printStackTrace();
            // 由于已经设置了响应类型，这里不能再返回JSON
            try {
                response.reset();
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                response.getWriter().println("{\"success\":false,\"message\":\"导出失败: " + e.getMessage() + "\"}");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    // 下载导入模板
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            // 创建示例数据
            List<OwnerDTO> examples = new ArrayList<>();
            OwnerDTO example = new OwnerDTO();
            example.setName("张三");
            example.setGender("男");
            example.setPhoneNumber("13800138000");
            example.setIdCard("110101199001011234");
            example.setProfession("工程师");
            example.setEmail("zhangsan@example.com");
            example.setRemarks("示例数据");
            examples.add(example);
            
            // 定义表头
            List<Map<String, Object>> headers = new ArrayList<>();
            headers.add(createHeader("姓名", "name", 15));
            headers.add(createHeader("性别", "gender", 10));
            headers.add(createHeader("电话号码", "phoneNumber", 20));
            headers.add(createHeader("身份证号", "idCard", 25));
            headers.add(createHeader("职业", "profession", 15));
            headers.add(createHeader("邮箱", "email", 25));
            headers.add(createHeader("备注", "remarks", 30));
            
            // 导出Excel
            ExcelUtil.exportExcel(response, "业主信息导入模板", examples, headers);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.reset();
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                response.getWriter().println("{\"success\":false,\"message\":\"下载模板失败: " + e.getMessage() + "\"}");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    // 导入业主
    @PostMapping("/import")
    public ResponseEntity<?> importOwners(@RequestParam("file") MultipartFile file) {
        try {
            // 定义表头映射
            List<Map<String, Object>> headers = new ArrayList<>();
            headers.add(createHeader("姓名", "name", 0));
            headers.add(createHeader("性别", "gender", 0));
            headers.add(createHeader("电话号码", "phoneNumber", 0));
            headers.add(createHeader("身份证号", "idCard", 0));
            headers.add(createHeader("职业", "profession", 0));
            headers.add(createHeader("邮箱", "email", 0));
            headers.add(createHeader("备注", "remarks", 0));
            
            // 解析Excel
            List<Map<String, Object>> data = ExcelUtil.importExcel(file, headers);
            
            // 转换为实体对象并保存
            List<Owner> owners = new ArrayList<>();
            for (Map<String, Object> row : data) {
                Owner owner = new Owner();
                owner.setName((String) row.get("name"));
                owner.setGender((String) row.get("gender"));
                owner.setPhoneNumber((String) row.get("phoneNumber"));
                owner.setIdCard((String) row.get("idCard"));
                owner.setProfession((String) row.get("profession"));
                owner.setEmail((String) row.get("email"));
                owner.setRemarks((String) row.get("remarks"));
                owners.add(owner);
            }
            
            // 批量保存
            ownerRepository.saveAll(owners);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "导入成功");
            response.put("successCount", owners.size());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "导入失败: " + e.getMessage()));
        }
    }

    // 辅助方法：创建表头配置
    private Map<String, Object> createHeader(String title, String field, int width) {
        Map<String, Object> header = new HashMap<>();
        header.put("title", title);
        header.put("field", field);
        if (width > 0) {
            header.put("width", width);
        }
        return header;
    }
} 